package demo12;

import java.util.ArrayList;
import java.util.List;

/*上例中，可以用synchronized解决，synchronized可以保证可见性和原子性，volatile只能保证可见性*/
public class T {
    int count = 0;

    synchronized void m() {  //m方法加了synchronized修饰，保证了原子性和可见性
        for (int i = 0; i < 10000; i++) {
            count++;
        }
    }

    public static void main(String[] args) {
        T t = new T();
        List<Thread> threads = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            threads.add(new Thread(t::m, "thread-" + i));
        }
        threads.forEach(Thread::start);
        threads.forEach((o) -> {
            try {
                o.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        System.out.println(t.count); //100000
    }
}